package base.thread_demo.demo18;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 需求：在指定的时间删除我们的指定目录(你可以指定c盘，但是我不建议，我使用项目路径下的demo)
 */
public class TimerFilesDelete {
    private static Logger logger = LoggerFactory.getLogger(TimerFilesDelete.class);

    public static void main(String[] args) throws ParseException {
        // 指定一个待删除的文件目录
        File file = new File("./demo");
        System.out.println(file.getName());
        // 创建一个定时任务
        Timer timer = new Timer();

        String s = "2020-12-29 13:17:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        timer.schedule(new DeleteFilesTask(file, timer), sdf.parse(s));
    }

}

/**
 * 删除文件任务
 */
class DeleteFilesTask extends TimerTask {
    private static Logger logger = LoggerFactory.getLogger(DeleteFilesTask.class);
    private File file;
    private Timer timer;
    public DeleteFilesTask(File file, Timer timer){
        this.file = file;
        this.timer = timer;
    }

    @Override
    public void run() {
        logger.info("开始执行删除文件......");
        del(file);
        timer.cancel();// 结束定时器
    }

    // 递归删除指定目录下文件
    public static void del(File file){
        File[] files = file.listFiles();
        if(files != null){
            for (File f: files) {
                if(f.isDirectory()){
                    del(f);
                }else {
                    boolean delete = f.delete();
                    logger.info("删除文件-> {}:{}", f.getName(), delete);
                }
            }
            logger.info("删除文件-> {}:{}", file.getName(), file.delete());
        }else{
            logger.info("没有文件要删除");
        }
    }
}
